package com.itany.Interceptor;

import com.itany.controller.SpringWebSocketHandler;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 在连接成功之前即onopen方法之前会先执行次拦截器
 */
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        System.out.println("=================beforeHandshake=====================");
        if(request instanceof ServletServerHttpRequest){
            ServletServerHttpRequest serverHttpRequest =  (ServletServerHttpRequest)request;
            HttpServletRequest httpServletRequest = serverHttpRequest.getServletRequest();
            HttpSession session = httpServletRequest.getSession(true);
            String websocketid = (String)session.getAttribute("SESSION_USERNAME");
            if(websocketid!=null){
                attributes.put(SpringWebSocketHandler.USER_ID,websocketid);
            }

        }
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response,
                               WebSocketHandler wsHandler, Exception ex) {
        System.out.println("=================afterHandshake=====================");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
